package com.itcam.controller;

import com.google.gson.Gson;
import com.itcam.pojo.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;


//5.json格式的参数获取 - @RequestBody
//6.Cookie数据的获取  - @CookieValue

@RestController
@RequestMapping("/hello05")
public class Hello05Controller {

    //1.演示获取请求体数据
    //http://localhost:8080/h01      请求体参数是： {"uname":"jim","age":20}
    @PostMapping("/h01")
//    public String h01(HttpServletRequest request) throws IOException {
//        BufferedReader br = request.getReader();
//        StringBuilder stringBuilder = new StringBuilder("");
//        String line = null;
//        while ((line = br.readLine()) != null) {
//            stringBuilder.append(line);
//        }
//        line = stringBuilder.toString();
//        Gson gson = new Gson();
//        User user = gson.fromJson(line, User.class);
//        System.out.println(user);
//        return "succ";
//    }
    public String h01(@RequestBody User user) {
        System.out.println(user);
        return "succ";
    }

    //2.此方法用于服务器端向客户端发送cookie数据
    @GetMapping("/h02_1")
    public String h02_1(HttpServletResponse response) {
        Cookie cookie = new Cookie("username", "jimgreen");
        cookie.setMaxAge(3600 * 60 * 24);
        response.addCookie(cookie);
        return "succ";
    }

    //3.此方法用于演示服务器端获取请求中的cookie数据
    //http://localhost:8080/h02
    @GetMapping("/h02")
    public String h02(@CookieValue("username") String uname) {
        System.out.println("uname = " + uname);
        return "succ";
    }

    //4.演示获取请求头数据
    @GetMapping("/h03")
    public String h03(@RequestHeader("Accept") String accept,
                      @RequestHeader("Accept-Encoding") String acceptEncoding,
                      @RequestHeader("Host") String host) {
        System.out.println("accept = " + accept);
        System.out.println("acceptEncoding = " + acceptEncoding);
        System.out.println("host = " + host);
        return "succ";
    }
}
